package com.heima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.PageResult;
import com.heima.exception.ErrorCode;
import com.heima.exception.GlobalException;
import com.heima.mapper.RoleMapper;
import com.heima.mapper.UserMapper;
import com.heima.pojo.Role;
import com.heima.pojo.User;
import com.heima.pojo.dto.LoginDto;
import com.heima.pojo.dto.PageUserDto;
import com.heima.pojo.vo.LoginUserVo;
import com.heima.pojo.vo.UserAddVo;
import com.heima.pojo.vo.UserVo;
import com.heima.service.UserService;
import com.heima.utils.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

import static com.sun.org.apache.xalan.internal.xsltc.compiler.Constants.CHARACTERS;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;;

    private static final String LOGIN_NAME = "小美";
    private static final String PASSWORD = "123456";
    String secret = generateRandomString();
    //生成8位不重复的字符串
    private static String generateRandomString() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 8; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }



    @Autowired
    private JwtUtil jwtUtil; // 注入 JWT 工具类

    @Override
    public LoginUserVo login(LoginDto dto) {

        if (dto == null || StringUtils.isBlank(dto.getLoginName()) || StringUtils.isBlank(dto.getPassword())) {
            throw new GlobalException(ErrorCode.USER_NOT_FOUND);
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getLoginName, dto.getLoginName());
        User user = userMapper.selectOne(wrapper);

        if (user == null) {
            throw new GlobalException(ErrorCode.USER_NOT_FOUND);
        }
        if (!user.getPassword().equals(dto.getPassword())) {
            throw new GlobalException(ErrorCode.PASSWORD_ERROR);
        }

        // 生成 JWT
        String token = jwtUtil.generateToken(user.getId());

        // 构建返回对象
        LoginUserVo loginUserVo = new LoginUserVo();
        BeanUtils.copyProperties(user, loginUserVo);
        loginUserVo.setSuccess(true);
        loginUserVo.setMsg("登录成功");
        loginUserVo.setToken(token);

        return loginUserVo;
    }

    @Override
    public PageResult<UserVo> search(PageUserDto pageUserDto) {
        Page<UserVo> page = new Page<>(pageUserDto.getPageIndex(), pageUserDto.getPageSize());
        IPage<UserVo> result = userMapper.pageUser(page,pageUserDto);
        return new PageResult<>(
                (int) page.getCurrent(),
                (int) page.getSize(),
                (int) result.getPages(),
                result.getTotal(),
                result.getRecords()
        );
    }

    @Override
    public List<Role> getRole() {
        return roleMapper.selectList(null);
    }

    @Override
    public Boolean saveUser(UserAddVo userAddVo) {
        User user = new User();
        BeanUtils.copyProperties(userAddVo,user);
        user.setLoginName(LOGIN_NAME);
        user.setPassword(PASSWORD);
        user.setSecret(secret);
        String roleCode = roleMapper.selectByRoleId(userAddVo.getRoleId());
        user.setRoleCode(roleCode);
        user.setRegionId(Long.valueOf(userAddVo.getRegionId()));
        user.setStatus(userAddVo.getStatus() ? (byte) 1 : (byte) 0);
        return super.save(user);
    }

    @Override
    public Boolean updateUser(Integer userId, UserAddVo userAddVo) {
        User user = new User();
        BeanUtils.copyProperties(userAddVo,user);
        return userMapper.updateById(userId,user) > 0;
    }


}
